package com.ooqiu.gaming.ui.web;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.ooqiu.gaming.ui.login.LoginActivity;
import com.ooqiu.gaming.ui.person.edit_profile.EditProfileActivity;
import com.ooqiu.gaming.ui.preview.PreviewPicActivity;
import com.ooqiu.gaming.ui.preview.QRCodePreviewActivity;
import com.ooqiu.gaming.utils.LogUtil;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DefaultSubscriber;

/**
 * @author mao
 * @version v1.0
 * @date 2017/4/7 21:18
 * @des 腾讯TBS浏览服务x5内核WebView
 * @link http://blog.csdn.net/github_2011/article/details/71600734
 */
public class X5WebView extends WebView {

    private Context mContext;

    private WebViewClient client = new WebViewClient() {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // 重写此方法可以让webview处理https请求
            handler.proceed();
        }


        //        @Override
//        public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {
//
//            LogUtil.e("url = " + webResourceRequest.getUrl().toString());
//            webResourceRequest.getRequestHeaders().put("Referer", "http://www.ooqiuimg.com/yyg/");
//            LogUtil.json(webResourceRequest.getRequestHeaders());
//
//
//            return super.shouldInterceptRequest(webView, webResourceRequest);
//        }


        //        @Override
//        public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest, Bundle bundle) {
//
//
//            if (webResourceRequest.getUrl().getHost().equals("wx.tenpay.com")) {
//                try {
//                    LogUtil.e("url = " + webResourceRequest.getUrl().toString());
//                    webResourceRequest.getRequestHeaders().put("Referer", "http://www.ooqiuimg.com/yyg/");
//                    LogUtil.json(webResourceRequest.getRequestHeaders());
//
//                    Request request = new Request.Builder()
//                            .url(webResourceRequest.getUrl().toString())
//                            .get()
//                            .addHeader("test", "something")
//                            .build();
//
//                    LogUtil.e("there");
//
//
//                    OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                            .connectTimeout(20000L, TimeUnit.MILLISECONDS)
//                            .readTimeout(20000L, TimeUnit.MILLISECONDS)
//                            .hostnameVerifier(new HostnameVerifier() {
//                                @Override
//                                public boolean verify(String hostname, SSLSession session) {
//                                    return true;
//                                }
//                            })
//                            .sslSocketFactory(sslParams.sSLSocketFactory,sslParams.trustManager)
//                            .build();
//
//
//
//
//
//
//                    Response response = new OkHttpClient.Builder().build()
//
//                            .newCall(request).execute();
//                    return new WebResourceResponse(response.body().contentType().toString(), "UTF-8", response.body().byteStream());
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            LogUtil.e("here");
//            return super.shouldInterceptRequest(webView, webResourceRequest, bundle);
//        }

        // 防止加载网页时调起系统浏览器
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            LogUtil.e("shouldOverrideUrlLoading = " + url);

            Uri uri = Uri.parse(url);
            String host = uri.getHost();

            if (!TextUtils.isEmpty(host) && host.equals("bbs.ooqiu.com")) {
                String action = uri.getQueryParameter("action");
                if (!TextUtils.isEmpty(action) && action.equals("login")) {
                    ARouter.getInstance().build(LoginActivity.PATH).navigation();
                    return true;
                }
                if (uri.getQueryParameterNames().contains("setting")) {
                    ARouter.getInstance().build(EditProfileActivity.PATH).navigation();
                    return true;
                }


            }

//            https://mclient.alipay.com/cashier/mobilepay.htm?alipay_exterface_invoke_assign_target=invoke_49c0c481bee43736b8c1bc82f021e716&alipay_exterface_invoke_assign_sign=e_x_e_i_j77kn_t_y0_utnyf_fz_wy01lisc_pau8g0_i_h%2B_y_bh_c4lid7_d418n_ea2_q%3D%3D
//            https://openapi.alipay.com/gateway.do?charset=UTF-8
//            if (host.equals("mclient.alipay.com") || url.startsWith("alipays:") || host.equals("openapi.alipay.com")) {
//
//                ARouter.getInstance().build(WebActivity.PATH)
//                        .withString("url", url)
//                        .navigation();
//                return true;
//            }


            // 获取上下文, H5PayDemoActivity为当前页面
            final Context context = view.getContext();
            // ------  对alipays:相关的scheme处理 -------
            if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                try {
                    context.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                } catch (Exception e) {
                    new AlertDialog.Builder(context)
                            .setMessage("未检测到支付宝客户端，请安装后重试。")
                            .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                    context.startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                }
                            })
                            .setNegativeButton("取消", null)
                            .show();
                }
                return true;
            }


//            if (!(url.startsWith("http") || url.startsWith("https"))) {
//                return true;
//            }

            if (url.startsWith("weixin://wap/pay?")) {
                LogUtil.e("startsWith");
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                context.startActivity(intent);
                return true;
            } else {
//                LogUtil.e("extraHeaders");
                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("Referer", "http://www.ooqiuimg.com");
                view.loadUrl(url, extraHeaders);
                return true;
            }

        }
    };

    public X5WebView(Context context) {
        super(context);
        mContext = context;


        setBackgroundColor(Color.parseColor("#f5f5f5"));
        this.setWebViewClient(client);
        // this.setWebChromeClient(chromeClient);
//         WebStorage webStorage = WebStorage.getInstance();
        initWebViewSettings();

        this.getView().setClickable(true);
    }

    @SuppressLint("SetJavaScriptEnabled")
    public X5WebView(Context context, AttributeSet arg1) {
        super(context, arg1);
        mContext = context;
        this.setWebViewClient(client);
        // this.setWebChromeClient(chromeClient);
//         WebStorage webStorage = WebStorage.getInstance();
        initWebViewSettings();

//        this.getView().setClickable(true);
    }

    private void initWebViewSettings() {
        WebSettings webSetting = this.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
//        webSetting.setAppCachePath(mContext.getExternalCacheDir() + File.separator + "webview");


        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSetting.setUserAgent(webSetting.getUserAgentString() + ";platform=android");

        CookieManager.getInstance().setAcceptThirdPartyCookies(this, true);


//        WebView.setSysDayOrNight(true);

        setOnLongClickListener(this);

//        setPictureListener(this);

    }


    @Override
    public boolean onLongClick(View view) {

        final HitTestResult htr = getHitTestResult();//获取所点击的内容
        LogUtil.e("type = " + htr.getType() + "   extra = " + htr.getExtra());
        if (htr.getType() == HitTestResult.IMAGE_TYPE) {
            showImgPopup(view, htr.getExtra());
            return true;
        }
        return false;
    }


    private void showImgPopup(View view, final String img_url) {
        AlertDialog dialog = new AlertDialog.Builder(mContext)
                .setItems(new String[]{"查看图片", "识别二维码"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                PreviewPicActivity.start(img_url);
                                break;
                            case 1:
                                Glide.with(mContext)
                                        .downloadOnly()
                                        .load(img_url).into(new SimpleTarget<File>() {
                                    @Override
                                    public void onStart() {
                                        LogUtil.e("download...");
                                    }

                                    @Override
                                    public void onResourceReady(File resource, Transition<? super File> transition) {
                                        LogUtil.e("path = " + resource.getAbsolutePath());
                                        Flowable.just(resource.getAbsolutePath())
                                                .subscribeOn(Schedulers.io()).
                                                map(new Function<String, String>() {
                                                    @Override
                                                    public String apply(String s) throws Exception {
                                                        return QRCodeDecoder.syncDecodeQRCode(s);
                                                    }
                                                })
                                                .observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(new DefaultSubscriber<String>() {
                                                    @Override
                                                    public void onNext(String s) {

                                                        LogUtil.e("decode = " + s);

                                                        if (TextUtils.isEmpty(s)) {
                                                            Toast.makeText(mContext, "图片不包含二维码信息", Toast.LENGTH_SHORT).show();
                                                        } else {
                                                            ARouter.getInstance().build(QRCodePreviewActivity.PATH).withString("decode_res", s)
                                                                    .navigation();
                                                        }
                                                    }

                                                    @Override
                                                    public void onError(Throwable t) {
                                                        t.getMessage();
                                                    }

                                                    @Override
                                                    public void onComplete() {

                                                    }
                                                });

                                    }
                                });


                                break;
                        }
                        dialog.dismiss();

                    }
                })
                .create();
        dialog.show();
//        QMUIPopup qmuiPopup = new QMUIPopup(mContext);
//        View v = LayoutInflater.from(mContext).inflate(R.layout.common_webview_img_popup, null);
//        qmuiPopup.setContentView(v);


//        RecyclerView menuList = v.findViewById(R.id.rv_webview_img_menu);
//        qmuiPopup.show(this);

    }


}
